#include "ahxgwnet.h"

namespace ahxgwnet {

Thread::Thread()
{
    m_tid = 0;
    m_pid = 0;
}

void Thread::start(Runnable *runnable, void *args)
{
    m_runnable  = runnable;
    m_args      = args;
    
    pthread_create(&m_tid, NULL, Thread::hook, this);
}

void Thread::join()
{
    if (m_tid)
    {
        pthread_join(m_tid, NULL);
        m_tid = 0;
        m_pid = 0;
    }
}

Runnable * Thread::getRunnable()
{
    return m_runnable;
}

void * Thread::getArgs()
{
    return m_args;
}

int Thread::getPid()
{
    return m_pid;
}

void *Thread::hook(void *arg)
{
    Thread *thread  = (Thread *)arg;
    thread->m_pid   = gettid();
    
    if (thread->getRunnable())
        thread->getRunnable()->run(thread, thread->getArgs());
    
    return (void *)NULL;
}

}
